<template>
  <div class="spmsColor" curPageName="spmsColor2132131243453">
    <layoutContent :toogleShow="false">
      <template #search>
        <!-- 搜索模块儿 -->
        <serachBar
          custom_class="myclass"
          :placeholder="$t('archive_set_supplierColor.supplier_color')"
          :close-advanced="true"
          :search_val="state.key_words"
          @searchEvent="searchFn"
        >
          <template #header>
            <div>
              <el-select
                v-model="state.supplier_id"
                filterable
             
                clearable
                :placeholder="$t('archive_set_supplierColor.all_spms')"
                remote-show-suffix
                
                style="width: 240px"
              >
                <el-option v-for="item in optionsSelectOne" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </template>
          <template #footer>
            <el-button type="primary" v-auth="{ authArr: authArr, key: 'addColor' }" @click="onPlus">{{
              $t("archive_set_supplierColor.add_color")
            }}</el-button>
          </template>
        </serachBar>
      </template>
      <template #content>
        <MerakXTable ref="tableRef" v-bind="tablePayload" :query-columns="handleQueryColumns" :query-data="handleQueryData">
          <template #handler="{ row }">
            <div style="display: flex">
              <el-button v-auth="{ authArr: authArr, key: 'editColor' }" type="primary" link @click="saveEdit(row)">
                {{ $t("merak.edit") }}
              </el-button>
              <el-button
                v-auth="{ authArr: authArr, key: 'delColor' }"
                :type="row.disable ? '' : 'danger'"
                link
                :disabled="row.disable"
                @click="delsupplierColor(row)"
              >
                {{ $t("merak.delete") }}
              </el-button>
            </div>
          </template>
        </MerakXTable>
      </template>
    </layoutContent>

    <!-- 弹窗模块儿 -->
    <div class="drawer">
       <el-drawer
        modal-class="merak_modal"
        v-model="drawerSupplierColor" 
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="700"
      >
        <template #header>
          <div class="merak_modal_title">{{ supplierColorTitle }}</div>
        </template>
        <div class="supplierColorPad">
          <el-form :model="supplierColorForm" ref="supplierColorRef" :rules="supplierColorRules" label-position="top">
        
                <el-form-item :label="$t('archive_set_supplierColor.supplier_color_ru')" prop="supplier_color_ru">
                  <el-input class="qf_input" v-model="supplierColorForm.supplier_color_ru" />
                </el-form-item>
 
                <el-form-item :label="$t('archive_set_supplierColor.supplier_color_cn')" prop="supplier_color_cn">
                  <el-input class="qf_input" v-model="supplierColorForm.supplier_color_cn" />
                </el-form-item>
          
                <el-form-item :label="$t('archive_set_supplierColor.supplier_name')" prop="supplier_id">
                  <el-select
                    class="qf_select"
                    style="width: 100%"
                    v-model="supplierColorForm.supplier_id"
                    :placeholder="$t('archive_set_supplierColor.placeholder_supplier')"
                    filterable
                    remote
                    clearable
                    default-first-option
                    reserve-keyword
                    remote-show-suffix
                    :remote-method="remoteMethodSelect"
                    :loading="loadingSelect"
                  >
                    <el-option v-for="cItem in optionsSelect" :key="cItem.value" :label="cItem.label" :value="cItem.value" />
                  </el-select>
                </el-form-item>
           
                <el-form-item :label="$t('archive_set_supplierColor.sort')">
                  <el-input class="qf_input" v-number maxlength="3" v-model="supplierColorForm.sort" />
                </el-form-item>
           
          </el-form>
        </div>

        <template #footer>
          <el-button type="default" @click="cancelEmpty(supplierColorRef)">{{ $t("merak.cancel") }}</el-button>
          <el-button type="primary" plain v-if="editShow" :loading="loadingState" @click="saveContinue('2', supplierColorRef)">{{
            $t("merak.save_continue")
          }}</el-button>
          <el-button type="primary" @click="submitForm('1', supplierColorRef)" :loading="loadingState">{{
            $t("merak.save")
          }}</el-button>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script setup lang="ts" name="spmsColor">
import { ref, reactive, computed, getCurrentInstance, nextTick, onMounted } from "vue";
import layoutContent from "@/components/LayoutComponents/index.vue";
import { getAlltree } from "@/minxins/useOrgsStore"; //获取组织架构树
import serachBar from "@/components/SearchBar/index";
import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";

import useLoading from "@/hooks/useLoading";
import { getLocationParams } from "@/utils/index";
// 使用队列 loading 管理初始化页面加载状态
const { queueLoading, queueId } = useLoading();

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
import {
  getSuppilerHeadApi,
  getSupplierListApi,
  editSupplierColorApi,
  delSupplierColorApi,
  getSuppilerListApi
} from "@/api/modules/goodsArchive/set/supplierColor";
import { ResultEnum } from "@/enums/httpEnum";

const tableRef = ref<MerakXTableInstance>();

//#region 表单编辑

const supplierColorRef = ref();
const loadingState = ref(false); //loading状态值
const { proxy } = getCurrentInstance();
const supplierColorTitle = ref(proxy.$t("archive_set_supplierColor.add_color"));
const drawerSupplierColor = ref(false);
const editShow = ref(true);
//表单参数结构
const supplierColorForm = ref({});
const supplierColorRules = reactive({
  supplier_color_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
  supplier_color_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
  sort: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
  supplier_id: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }]
});

//保存并添加
const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
  submitForm(typebtn, formEl);
};
//保存

const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //保存
      loadingState.value = true;
      editSupplierColorApi(supplierColorForm.value)
        .then(res => {
          console.log(res);
          loadingState.value = false;
          if (res.code == ResultEnum.SUCCESS) {
            successMsg(proxy.$t("merak.action_success"));
            if (typebtn == 1) {
              //关闭弹窗
              drawerSupplierColor.value = false;
            }
            formEl.resetFields();
            supplierColorForm.value = resetForm(); //清空表单
            tableRef.value?.reloadData(); //刷新表格
            initSupplier()
            return;
          } else {
            failMsg(res.message);
          }
          // if (res.code == ResultEnum.ERROR) {

          // }
        })
        .catch(err => {
          loadingState.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//删除
const delsupplierColor = rows => {
  delConfimMsg({
    callback: val => {
      if (val == "confirm") {
        delSupplierColorApi({ supplier_color_id: rows.supplier_color_id }).then(res => {
          if (res.code == ResultEnum.SUCCESS) {
            successMsg(proxy.$t("merak.delete_success"));
            tableRef.value?.reloadData();
          }
          if (res.code == ResultEnum.ERROR) {
            failMsg(res.message);
          }
        });
      }
    }
  });
};

//编辑
const saveEdit = rows => {
  console.log(rows);
  let { supplier_color_id, supplier_id, supplier_color_cn, supplier_color_ru, sort, supplier_name } = JSON.parse(
    JSON.stringify(rows)
  );
  //打开弹窗
  drawerSupplierColor.value = true;
  remoteMethodSelect(supplier_name).then(() => {
    console.log("chufa.....");
    nextTick(() => {
      supplierColorRef.value?.resetFields();
      supplierColorForm.value = {
        supplier_color_id: supplier_color_id, //组织id  新增时不需要
        supplier_id: supplier_id, //供应商id
        supplier_color_cn: supplier_color_cn, //商家颜色(中文)
        supplier_color_ru: supplier_color_ru, //商家颜色(俄文)
        sort: sort //排序
      };
      console.log(supplierColorForm.value, "绑定只");

      editShow.value = false;

      supplierColorTitle.value = proxy.$t("archive_set_supplierColor.edit_color");
    });
  });
};
//取消
const cancelEmpty = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  drawerSupplierColor.value = false;
};
//新增
const onPlus = () => {
  drawerSupplierColor.value = true;
  editShow.value = true;
  supplierColorTitle.value = proxy.$t("archive_set_supplierColor.add_color");
  supplierColorForm.value = resetForm();
};
const resetForm = () => {
  supplierColorRef.value?.resetFields();
  return {
    supplier_color_id: 0, //组织id  新增时不需要
    supplier_id: "", //供应商id
    supplier_color_cn: "", //商家颜色(中文)
    supplier_color_ru: "", //商家颜色(俄文)
    sort: "" //排序
  };
};

// 新建搜索查询
const loadingSelect = ref(false);
const optionsSelect = ref([]);
const optionsSelectOne = ref([]);

const remoteMethodSelect = (query: string) => {
  return new Promise((resolve, reject) => {
    if (query) {
      loadingSelect.value = true;
      getSuppilerListApi({ supplier_name: query, in_list:0 }).then(res => {
        loadingSelect.value = false;
        if (res.code == ResultEnum.SUCCESS) {
          let data = res.data; 
          if (data.length > 50) {
            if (drawerSupplierColor.value) {
              //弹窗打开
              optionsSelect.value = data.slice(0, 100);
             
            }
           
          } else {
            if (drawerSupplierColor.value) {
              optionsSelect.value = data;
              
            }
          
          }
       
          resolve();
        }
      });
    } else {
      optionsSelect.value = [];
    }
  });
};

//#endregion

//#region 列表

// 页面配置数据
let authArr = ref({});
const state = reactive<{
  supplier_id: string;
  key_words: string;
  columnType: Object;
}>({
  supplier_id: "",
  key_words: "",
  columnType: {}
});

// 动态计算表格的外部筛选数据
const params = computed(() => ({ key_words: state.key_words, supplier_id: state.supplier_id }));
const columnTypeNew = computed(() => [].concat(state.columnType));

// 表格配置属性
const tablePayload = reactive<MerakXTableProps>({
  // 列设置存储的数据对照值
  columnsByStore: [],
  // 表格行数据的唯一 key, 跟后端同步
  rowKey: "org_id",
  // 初始化的外部筛选数据
  params,

  //导出
  enabledExport: false,
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  columnType: columnTypeNew,
  // columnType: ['selection', "multiple", "handle"],
  // 批量操作选项
  batches: [{ type: "delete", text: "批量删除", color: "red" }]
  // 操作列选项
  // handles: [{ type: "delete", text: "删除", color: "red" }]
});

//获取数据
//查询

const searchFn = e => {
  state.key_words = e.search;
};
// const getDepFun = (e) => {
// 	console.log(e)
// 	state.org_id = e;
// }
//列表内容展示区
const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    Object.assign(params, { ...page }, from);
  }
  return await getSupplierListApi(params).then(res => {
    //  ========权限判断 start  ======
    let authList = res?.auth_list;
    if (authList) {
      authArr.value = authList;
      if (authList?.editColor.show || authList?.delColor.show) {
        state.columnType = { type: "handle", width: proxy.$t("lang") == "zh" ? 120 : 220, slot: "handler" };
      }
      tablePayload.enabledExport = !!res?.auth_list?.export?.show;
    }
    // ========权限判断 end  ======
    // 数据接口 start  ======
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data;
      const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

      return table_data;
    }
  });
};

// 获取表头数据
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return getSuppilerHeadApi().then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      // 克隆表头数据作为列设置的对照数据
      tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data
      };
    }
  });
};
//#endregion

//#region  初始化接口
const initSupplier=()=>{
    getSuppilerListApi({  in_list: 1 }).then(res => {
        loadingSelect.value = false;
        if (res.code == ResultEnum.SUCCESS) {
          let data = res.data; 
          if (data.length > 50) { 
            // 页面展示
            optionsSelectOne.value = data.slice(0, 100);
          } else { 
            // 页面展示
            optionsSelectOne.value = data;
          } 
        }
      });
}
 
onMounted(() => {
  initSupplier();
});
//#endregion
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
